import {
  login,
  logout,
  getUserInfo,
  getMessage,
  getContentByMsgId,
  hasRead,
  removeReaded,
  restoreTrash
} from '@/api/user'
import {
  setToken,
  getToken,
  setUserName,
  getUserName,
  setRoleId,
  getRoleId
} from '@/libs/util'

export default {
  state: {
    userName: '',
    userId: '',
    avatorImgPath: '',
    roleName: '',
    roleId: getRoleId(),
    mobile: '',
    name: '',
    no: '',
    email: '',
    password: '',
    unit: '',
    nationPlace: '',
    major: '',
    education: '',
    introduce: '',
    telephone: '',
    loginName: '',
    token: getToken(),
    access: '',
    hasGetInfo: false,
    messageUnreadList: [],
    messageReadedList: [],
    messageTrashList: [],
    messageContentStore: {}
  },
  mutations: {
    setAvator(state, avatorPath) {
      state.avatorImgPath =
        process.env.API_ROOT.replace('wisdom-classroom/', '') +
        'images/photo/' +
        avatorPath
    },
    setUserId(state, id) {
      state.userId = id
    },
    setUserName(state, name) {
      state.userName = name
      setUserName(name)
    },
    setRoleName(state, roleName) {
      state.roleName = roleName
    },
    setRoleId(state, roleId) {
      state.roleId = roleId
      setRoleId(roleId)
    },
    setMobile(state, mobile) {
      state.mobile = mobile
    },
    setName(state, name) {
      state.name = name
    },
    setNo(state, no) {
      state.no = no
    },
    setEmail(state, email) {
      state.email = email
    },
    setUnit(state, unit) {
      state.unit = unit
    },
    setNativePlace(state, nativePlace) {
      state.nativePlace = nativePlace
    },
    setMajor(state, major) {
      state.major = major
    },
    setEducation(state, education) {
      state.education = education
    },
    setIntroduce(state, introduce) {
      state.introduce = introduce
    },
    setLoginName(state, loginName) {
      state.loginName = loginName
    },
    
    
    setTelephone(state, telephone) {
      state.telephone = telephone
    },
    
    
    setPassword(state, password) {
      state.password = password
    },
    setAccess(state, access) {
      state.access = access
    },
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    setHasGetInfo(state, status) {
      state.hasGetInfo = status
    },
    setMessageUnreadList(state, list) {
      state.messageUnreadList = list
    },
    setMessageReadedList(state, list) {
      state.messageReadedList = list
    },
    setMessageTrashList(state, list) {
      state.messageTrashList = list
    },
    updateMessageContentStore(state, { msg_id, content }) {
      state.messageContentStore[msg_id] = content
    },
    moveMsg(state, { from, to, msg_id }) {
      const index = state[from].findIndex(_ => _.msg_id === msg_id)
      const msgItem = state[from].splice(index, 1)[0]
      msgItem.loading = false
      state[to].unshift(msgItem)
    }
  },
  getters: {
    messageUnreadCount: state => state.messageUnreadList.length,
    messageReadedCount: state => state.messageReadedList.length,
    messageTrashCount: state => state.messageTrashList.length
  },
  actions: {
    // 登录
    handleLogin({ commit }, { userName, password }) {
      userName = userName.trim()
      return new Promise((resolve, reject) => {
        login({
          userName,
          password
        })
          .then(res => {
            if (res.data.code == '0') {
              const data = res.data
              commit('setToken', data.data.token)
              commit('setUserName', userName)
              resolve(res.data.data)
            } else {
              reject(res.data.msg)
            }
          })
          .catch(err => {
            reject(err)
          })
      })
    },
    // 退出登录
    handleLogOut({ state, commit }) {
      return new Promise((resolve, reject) => {
        logout(state.token)
          .then(() => {
            commit('setToken', '')
            commit('setAccess', [])
            resolve()
          })
          .catch(err => {
            reject(err)
          })
        // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
        // commit('setToken', '')
        // commit('setAccess', [])
        // resolve()
      })
    },
    // 获取用户相关信息
    getUserInfo({ state, commit }, roleId) {
      let userName = getUserName()
      return new Promise((resolve, reject) => {
        try {
          getUserInfo(userName)
            .then(res => {
              console.log(roleId || state.roleId)
              if (res.data.user.roleId == (roleId || state.roleId)) {
                const data = res.data
                commit('setAvator', data.user.photo)
                commit('setUserName', data.user.loginName)
                commit('setUserId', data.user.id)
                commit('setName', data.user.name)
                commit('setMobile', data.user.mobile)
                commit('setNo', data.user.no)
                commit('setEmail', data.user.email)
                commit('setUnit', data.user.unit)
                commit('setNativePlace', data.user.nativePlace)
                commit('setMajor', data.user.major)
                commit('setEducation', data.user.education)
                commit('setIntroduce', data.user.introduce)
                commit('setLoginName', data.user.loginName)
                commit('setPassword', data.user.password)
                commit('setTelephone', data.user.telephone)
                commit('setAccess', data.menus)
                commit('setRoleName', data.role.roleName)
                commit('setRoleId', data.role.id)
                commit('setHasGetInfo', true)
                resolve(data)
              } else {
                reject('请选择正确的角色入口登录')
              }
            })
            .catch(err => {
              reject(err)
            })
        } catch (error) {
          reject(error)
        }
      })
    },
    // 获取消息列表，其中包含未读、已读、回收站三个列表
    getMessageList({ state, commit }) {
      return new Promise((resolve, reject) => {
        getMessage()
          .then(res => {
            const { unread, readed, trash } = res.data
            commit(
              'setMessageUnreadList',
              unread.sort(
                (a, b) => new Date(b.create_time) - new Date(a.create_time)
              )
            )
            commit(
              'setMessageReadedList',
              readed
                .map(_ => {
                  _.loading = false
                  return _
                })
                .sort(
                  (a, b) => new Date(b.create_time) - new Date(a.create_time)
                )
            )
            commit(
              'setMessageTrashList',
              trash
                .map(_ => {
                  _.loading = false
                  return _
                })
                .sort(
                  (a, b) => new Date(b.create_time) - new Date(a.create_time)
                )
            )
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 根据当前点击的消息的id获取内容
    getContentByMsgId({ state, commit }, { msg_id }) {
      return new Promise((resolve, reject) => {
        let contentItem = state.messageContentStore[msg_id]
        if (contentItem) {
          resolve(contentItem)
        } else {
          getContentByMsgId(msg_id).then(res => {
            const content = res.data
            commit('updateMessageContentStore', { msg_id, content })
            resolve(content)
          })
        }
      })
    },
    // 把一个未读消息标记为已读
    hasRead({ commit }, { msg_id }) {
      return new Promise((resolve, reject) => {
        hasRead(msg_id)
          .then(() => {
            commit('moveMsg', {
              from: 'messageUnreadList',
              to: 'messageReadedList',
              msg_id
            })
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 删除一个已读消息到回收站
    removeReaded({ commit }, { msg_id }) {
      return new Promise((resolve, reject) => {
        removeReaded(msg_id)
          .then(() => {
            commit('moveMsg', {
              from: 'messageReadedList',
              to: 'messageTrashList',
              msg_id
            })
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 还原一个已删除消息到已读消息
    restoreTrash({ commit }, { msg_id }) {
      return new Promise((resolve, reject) => {
        restoreTrash(msg_id)
          .then(() => {
            commit('moveMsg', {
              from: 'messageTrashList',
              to: 'messageReadedList',
              msg_id
            })
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    }
  }
}
